//公司管理
// 日期区间
laydate.render({
    elem: '#between'
    ,range: true
  });

// 添加公司记录跳转
$('#add').on('click',()=>{
    window.location.href = "{:url('html/system/company_add')}";
})
var page = 1;
var pagenum = 10;
var fi=1;
var url={
    list:api.company.list,
    delete:api.company.delete,
    add:api.company.add,
    edit:api.company.edit,
    down:api.company.down
}
var main=[[ //表头
	{if $Think.get.op}
	{ title: '操作',minWidth:150, toolbar:'#operation1',fixed: 'left'},
	{else/}
     {type:'checkbox', fixed: 'left'},
     {/if}
    {field: 'company_name', title: '公司名称',  width: 180, fixed: 'left'}
    ,{field: 'company_mode', title: '公司类型',width: 100,templet:'<div>{{d.company_mode==1?"单位":"服务公司"}}</div>'}
    ,{field: 'account', title: '账号',width: 140,templet:'<div>{{d.account?d.account:"无账号"}}</div>'}  
    ,{field: 'unit_quota', title: '单位额度',width:110}
    ,{field:'used_unit_quota', title:'单位余额',width:110,templet:'<div>{{d.unit_quota - d.used_unit_quota}}</div>'}
    ,{field: 'quota', title: '财政额度',width:110}
    ,{field:'used_quota', title:'财政余额',width:110,templet:'<div>{{d.quota - d.used_quota}}</div>'}
    ,{field:'linkman', title:'联系人',templet:'<div>{{d.linkman?d.linkman:"-"}}</div>',width:120}
    ,{field:'phone', title:'联系电话',width:140,templet:'<div>{{d.phone?d.phone:"-"}}</div>'}
    ,{field:'state', title:'状态',width:100,templet:'<div><div style="color:{{d.state==9?"red":"green"}}">{{d.state==9?"禁用":"已启用"}}</div></div>'}
    
    {if $Think.get.op}
     
	{else/}
//	 ,{ title: '详情', toolbar:'#detail',width:80,fixed: 'right',align:"center"}
    ,{ title: '操作',minWidth:170, toolbar:'#operation',fixed: 'right'}
     {/if}
]];
var data={};
data.page=page;
data.pagenum=pagenum;

var where_json ={};

{if $Think.get.company_name}
where_json.company_name=['like','{$Think.get.company_name}']
{/if}
{if $Think.get.company_mode}
where_json.company_mode=['like','{$Think.get.company_mode}']
{/if}
{if $Think.get.prop}
where_json.prop=['like','{$Think.get.prop}']
{/if}

data.where_json=JSON.stringify(where_json)

ajaxsevice(data);
function ajaxsevice(data) {
    Load();
    //请求数据
    ajax(url.list, data, 'post').done(function (resp) {
        Load(1);
        // 成功回调
        //方法级表单渲染
        console.log(resp)
        table.render({
            elem: '#company',
            cols: main,
            data: resp.data,
            limit: pagenum,
            cellMinWidth: 80
        });
        if(resp.code == 1){
        
        if (fi == 1) {
            laypage.render({
                elem: 'page',
                count: resp.count,
                layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                theme: '#1E9FFF',
                jump: function (obj, first) {
                    console.log(obj)
                    if (!first) {
                        page = obj.curr;
                        data.page = page;
                        pagenum = obj.limit;
                        data.pagenum = pagenum;
                        ajaxsevice(data);
                    } else {

                    }
                }
            })
            fi = 2;
        }
        {if $Think.get.op}
         table.on('tool(company)', function (obj) {
         	 var data1 = obj.data; 
         	//获得当前行数据
			var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
			var tr = obj.tr; //获得当前行 tr 的DOM对象
			if(layEvent === 'choose') {
				var index = parent.layer.getFrameIndex(window.name);
				console.log(data1)
				{if $Think.get.op=='entrust'}
					parent.$('.entrust_company_id').val(data1.company_id)
					parent.$('.entrust_company_name').val(data1.company_name)
				{else/}
					parent.$('.company_id').val(data1.company_id)
					parent.$('.company_name').val(data1.company_name)
				{/if}
				if(parent.$('.company_name').data('people')=='apply'){
					ajax(api.passenger.list,{
						where_json:JSON.stringify({
							company_id:['in',data1.company_id]
						})
					},'post').done((res)=>{
						if(res.code==1){
							var options=`<option value='0'>请选择申请人</option>`
							for(var i=0;i<res.data.length;i++){
								options+=`<option value='${res.data[i].passenger_id}'>${res.data[i].name}</option>`
							}
							parent.$('.user_id').html(options)
							parent.layui.form.render('select')
							parent.layer.close(index);
						}else{
							Err('请求失败')
						}
					}).fail(()=>{})
				}else{
					parent.layer.close(index);
				}
//				parent.layer.close(index);
			}
         })
        {else/}
        // 操作
        table.on('tool(company)', function (obj) {
                    var data1 = obj.data; //获得当前行数据
                    var data2 = {
                        company_ids:data1.company_id
                    };
                    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    var tr = obj.tr; //获得当前行 tr 的DOM对象
                    if (layEvent === 'edit') {
                        console.log('编辑')
                        window.location.href = "{:url('/html/system/company_add')}?company_id="+data1.company_id;
                    } else if (layEvent === 'del') {
                        layer.confirm('是否删除', function (index) {
                                Load()
                                ajax(url.delete, data2, 'post').done(function (res) {
                                   if(res.code==1){
                                   	console.log(res)
                                    layer.closeAll();
                                    Msg('删除成功');
                                    ajaxsevice(data)
                                   }else{
                                   	Err(res.msg)
                                   }
                                   // 成功回调
                                    
                                }).fail(function (err) {
                                    // 失败回调
                                    layer.close(deleteload);
                                    Err(res.msg ? res.msg : '操作失败，稍候再试');
                                });
                                layer.close(index);
                            })
                        }else if(layEvent == "forbidden"){
                                console.log("禁止")
                        }
                        else if(layEvent == 'detail'){
                            console.log("详情")
                                var company_id = data1.company_id;
                                console.log(company_id)
                                var detail = layer.open({
                                    type: 1,
                                    title:false,
                                    skin: 'layui-layer-rim', //加上边框
                                    area: ['200px', '100px'], //宽高
                                    content: `
                                      <table style='width:100%;height:'100%;' data-caruseid="${company_id}">
                                          <tbody>
                                        <tr>
                                        <td data-id="{$item.car_rental_id}">
                                        <div style="margin:39px 0 0 6.8px;">
                                            <a class="layui-btn layui-btn-primary layui-btn-xs department"  >部门</a>
                                        </div>
                                        </td>
                                        <td data-id="{$item.car_rental_id}" >
                                        <div style="margin:39px 0 0 6.8px;">
                                            <a class="layui-btn layui-btn-primary layui-btn-xs passenger" > 乘客</a>
                                        </div>
                                        </td>
                                        <td data-id="{$item.car_rental_id}" >
                                        <div style="margin:39px 0 0 6.8px;">
                                            <a class="layui-btn layui-btn-primary layui-btn-xs order">订单</a>
                                        </div>
                                        </td>
                                        <td data-id="{$item.car_rental_id}">
                                        <div style="margin:39px 0 0 6.8px;">
                                            <a class="layui-btn layui-btn-primary layui-btn-xs "> 报表</a>
                                        </div>
                                        </td>
                                        </tr>
                                        </tbody>
                                      </table>
                                  `
                                });
                                $('.department').on('click', function() {
                                	Load()
                                	ajax(api.company.department,{
                                		company_id:data1.company_id
                                	},'post').done((res)=>{
                                		 Load(1)
                                		console.log(res)
                                		var department_main=[[
                                		{field: 'company_name', title: '公司名称',  width: 180, fixed: 'left'}
                                		,{ title: '操作',minWidth:170, toolbar:'#operation2',fixed: 'right'}
                                		]]
                                	}).fail(()=>{})
                                    layer.close(detail);
                                   
                                });
                                $('.passenger').on('click', function() {
                                    
                                    layer.close(detail);
                                    
                                  
                                });
                                $('.order').on('click', function() {
                                    layer.close(detail);
                                    
                                });
                           
                        }
                    })
        			{/if}
            			//删除多个
    			$(".delete-multiple").on('click', function () {
    				var company_ids = '';
    				var checkStatus = table.checkStatus('company'); //test即为基础参数id对应的值
    				console.log(checkStatus.data) //获取选中行的数据
    				console.log(checkStatus.data.length) //获取选中行数量，可作为是否有选中行的条件
                    console.log(checkStatus.isAll) //表格是否全选
                    if(checkStatus.data.length){
    				for (var dei = 0; dei < checkStatus.data.length; dei++) {
    					if (dei == 0) {
    						company_ids += checkStatus.data[dei].company_id
    					} else {
    						company_ids += ("," + checkStatus.data[dei].company_id)
    					}
    				}
                    console.log(company_ids)
                    var data2 ={
                        company_ids : company_ids
                    }
    				layer.open({
    					type: 1,
    					title: false,
    					id: "delete",
    					content: '<div style="padding: 20px 100px;">是否删除</div>',
    					btn: ['确定', '取消'],
    					btnAlign: 'c' //按钮居中
    						,
    					shade: 0 //不显示遮罩
    						,
    					yes: function () {
    						var deleteload = layer.load(1, {
    							shade: [0.1, '#fff'] //0.1透明度的白色背景
                            });
                            
                            ajax(url.delete,data2,'post').done(function(resp) {
                                // 成功回调
                            			layer.close(deleteload);
                                        layer.closeAll();
                                        Msg('删除成功');
                                        ajaxsevice(data)
                                }).fail(function(err) {
                                // 失败回调
                                layer.close(deleteload);
    						    Err(res.msg ? res.msg : '操作失败，稍候再试');
                                });
    					},
    					btn2: function () {
    						layer.closeAll();
    					}
                    });
                }else{
                    Err('未有选择项')
                }
    			});
    }else{
        Err(resp.msg)
    }
    }).fail(function (err) {
        // 失败回调
        Load(1)
        Err('请求失败')
    });
};
